#!/usr/bin/env python3
"""
缓存管理器模块
- 管理已处理文件列表
- 管理转录状态缓存
- 管理失败记录
- 支持断点续传
"""

import json
import os
from typing import Dict, List
from pathlib import Path


class CacheManager:
    """缓存管理器"""

    def __init__(self, config: Dict):
        """
        初始化缓存管理器

        Args:
            config: cache配置
        """
        self.cache_dir = config.get('dir', './cache')
        self.processed_files_path = config.get(
            'processed_files', './processed_files.json'
        )
        self.failed_works_path = config.get(
            'failed_works', './failed_works.json'
        )
        self.status_cache_path = os.path.join(
            self.cache_dir, 'work_status_cache.json'
        )

        # 确保目录存在
        os.makedirs(self.cache_dir, exist_ok=True)

        # 加载缓存
        self.processed_files = self._load_json(self.processed_files_path, {})
        self.failed_works = self._load_json(self.failed_works_path, {})

    def is_file_processed(self, file_path: str) -> bool:
        """检查文件是否已处理"""
        return file_path in self.processed_files.get('processed', [])

    def mark_file_processed(self, file_path: str, result: Dict):
        """标记文件已处理"""
        if 'processed' not in self.processed_files:
            self.processed_files['processed'] = []

        self.processed_files['processed'].append(
            {
                'file_path': file_path,
                'file_name': os.path.basename(file_path),
                'processed_time': self._now(),
                'batch_id': result.get('batchId'),
                'created': result.get('created', 0),
                'skipped': result.get('skipped', 0),
                'status': 'completed',
            }
        )

        self._save_json(self.processed_files_path, self.processed_files)

    def save_batch_status(self, batch_id: int, need_transcribe: List[Dict]):
        """保存批次状态"""
        status = {
            'batch_id': batch_id,
            'need_transcribe': need_transcribe,
            'start_time': self._now(),
        }
        self._save_json(self.status_cache_path, status)

    def mark_transcribed(self, work_id: str):
        """标记作品已转录"""
        # 实现略
        pass

    def save_failed_work(self, work: Dict, error: str):
        """保存失败记录"""
        if 'failed' not in self.failed_works:
            self.failed_works['failed'] = []

        self.failed_works['failed'].append(
            {
                'platform': work.get('platform'),
                'workId': work.get('workId'),
                'savePath': work.get('savePath'),
                'error': error,
                'failed_time': self._now(),
                'retry_count': 0,
            }
        )

        self._save_json(self.failed_works_path, self.failed_works)

    def _load_json(self, file_path: str, default=None):
        """加载JSON文件"""
        if not os.path.exists(file_path):
            return default or {}
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                return json.load(f)
        except:
            return default or {}

    def _save_json(self, file_path: str, data: Dict):
        """保存JSON文件"""
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)

    def _now(self) -> str:
        """获取当前时间字符串"""
        from datetime import datetime

        return datetime.now().strftime('%Y-%m-%d %H:%M:%S')
